﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Entities.PlatAdmin;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using SqlSugar;
using Wq.Core.Common.Helper;
using Wq.Core.Extensions;
using Wq.Core.Extensions.Assembly.AutoMapper;
using Wq.Core.Extensions.Assembly.Redis;
using Wq.Core.Extensions.Assembly.SqlSugar;
using Wq.Core.Extensions.ServiceExtensions.Framework;
using Wq.Core.Model;
using Wq.Core.PlatAdminService.Models;

namespace Wq.Core.PlatAdminService
{
    public  class ManagerService : BaseRepository<ManagerInfo>, IRegister
    {
        public void Create(ManagerEditor manager)
        {
            manager.PasswordSalt = EncryptionHelper.BuildSalt();
            manager.Password = EncryptionHelper.GetPasswrodWithTwiceEncode(manager.Password, manager.PasswordSalt);
          
            var info = manager.Map<ManagerInfo>();
            info.CreateDate = DateTime.Now;
          info.Id = Context.Insertable(info).ExecuteReturnIdentity();
        }

        public void Save(ManagerEditor manager)
        {
            manager.PasswordSalt = EncryptionHelper.BuildSalt();
            manager.Password = EncryptionHelper.GetPasswrodWithTwiceEncode(manager.Password, manager.PasswordSalt);
            var info = manager.Map<ManagerInfo>();
            Context.Updateable(info).ExecuteCommand();
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="pageModel"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public List<ManagerView> List(PageModel<ManagerQuery> pageModel, ref int count)
        {
          return  Context.Queryable<ManagerInfo>().LeftJoin<RoleInfo>((p ,r) => p.RoleId == r.Id)
                .WhereIF(!SqlFunc.IsNullOrEmpty(pageModel.Entity.UserName),p => p.UserName.Contains(pageModel.Entity.UserName))
                .WhereIF(!SqlFunc.HasNumber(pageModel.Entity.RoleId),P => P.RoleId == pageModel.Entity.RoleId.Value)
                
                .Select<ManagerView>()
                .ToPageList(pageModel.Page.Index, pageModel.Page.Size, ref count);
        }

    }
}
